﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using FastReflectionLib;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.QY.Entities;
using System.Net;
using SZHL.UI.AppCode;
using SZHL.Data;

namespace SZHL.UI.API
{
    public class AuthManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(AuthManage).GetMethod(msg.Action.ToUpper());
            AuthManage model = new AuthManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }


        public void LOGIN(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strPassWord = context.Request["password"] ?? "";

            JH_Auth_UserB BUser = new JH_Auth_UserB();
            int count = BUser.GetEntities(d => d.UserName == UserInfo.User.UserName && d.UserPass == strPassWord && d.IsUse == "Y").Count();
            if (count == 0)
            {
                msg.ErrorMsg = "用户名或密码错误";
            }

        }
        public void MODIFYPWD(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == P2)
            {
                new JH_Auth_UserB().UpadteMiMa(UserInfo.User.UserName, P1);
            }
            else
            {
                msg.ErrorMsg = "确认密码不一致";
            }
        }
        /// <summary>
        /// 获取前端需要的人员选择列表
        /// </summary>
        public void GETUSERJS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtUsers = new JH_Auth_UserB().GetDTByCommand(" SELECT UserName,UserRealName FROM JH_Auth_User");
            //获取选择用户需要的HTML和转化用户名需要的json数据
            msg.Result = dtUsers;
        }


        public void GETPMENU(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_MenuB().GetMainMenuByUserName(UserInfo.User.UserName);
            msg.Result = dt;
        }
        /// <summary>
        /// 获取二级菜单
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P">一级菜单ID</param>
        /// <param name="strUserName"></param>
        public void GETMENU(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_MenuB().GetChiMenuByUserName(UserInfo.User.UserName, P1);
            msg.Result = dt;
        }

        public void GETLISTDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_FormBase FormBaseData = new JH_Auth_FormBaseB().GetEntity(d => d.FormCode == P1);

            string strFormTable = FormBaseData.FormTable;
            if (!string.IsNullOrEmpty(FormBaseData.FormGetSQL))
            {
                strFormTable = " (" + FormBaseData.FormGetSQL + ") as Form ";
            }
            DataTable dtResult = new DataTable();
            dtResult = new JH_Auth_FormBaseB().GetDTByCommand(" select  * from  " + strFormTable + " where 1=1  ORDER BY ID DESC");
            msg.Result = dtResult;
        }
        /// <summary>
        /// 根据部门编号获取部门人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETUSERBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = 1;
            }
            msg.Result = new JH_Auth_UserB().GetUserListbyBranch(deptCode, P2);
        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETBRANCH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = -1;
            }
            msg.Result = new JH_Auth_BranchB().GetBranchListByCode(deptCode);
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = " where r.PRoleCode<>-1";
            if (P1 != "")
            {
                strWhere = string.Format(" where  r.roleType='{0}'", P1);
                if (P2 != "")
                {
                    msg.Result1 = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == int.Parse(P2));
                }
            }
            msg.Result = new JH_Auth_RoleB().GetDTByCommand(@" select r.RoleCode,r.RoleName,COUNT(u.UserName) userCount from JH_Auth_Role r left join JH_Auth_UserRole ur on r.RoleCode=ur.RoleCode
                                                               left join JH_Auth_User u on ur.UserName=u.UserName " + strWhere + " group by r.RoleCode,r.RoleName ");

        }

        public void EDITROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_Role role = new JH_Auth_Role();
            role = JsonConvert.DeserializeObject<JH_Auth_Role>(P1);
            if (role.RoleCode != 0)
            {
                if (!new JH_Auth_RoleB().Update(role))
                {
                    msg.ErrorMsg = "修改角色失败";
                }

            }
            else
            {
                JH_Auth_Role user1 = new JH_Auth_RoleB().GetEntity(d => d.RoleName == role.RoleName);
                if (user1 != null)
                {
                    msg.ErrorMsg = "角色已存在";
                    return;
                }
                if (!new JH_Auth_RoleB().Insert(role))
                {
                    msg.ErrorMsg = "添加角色失败";
                }
            }
            if (P2 != "" && msg.ErrorMsg == "")
            {
                try
                {
                    new JH_Auth_UserRoleB().Delete(d => d.RoleCode == role.RoleCode);
                    foreach (string name in P2.Split(','))
                    {
                        string strSQL = string.Format("INSERT INTO  [JH_Auth_UserRole] ([UserName]  ,[RoleCode]) VALUES  ('{0}'  ,'{1}')", name, role.RoleCode);
                        new JH_Auth_UserRoleB().ExsSql(strSQL);
                    }
                }
                catch (Exception ex)
                {
                    msg.ErrorMsg = ex.Message;
                }
            }

        }
        public void DELROLE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            new JH_Auth_RoleB().delRole(int.Parse(P1));
            msg.ErrorMsg = "";
        }
        public void GETROLEBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_RoleB().GetEntity(d => d.RoleCode.ToString() == P1);
            msg.Result1 = new JH_Auth_UserRoleB().GetEntities(d => d.RoleCode.ToString() == P1).Select(d => d.UserName).ToList().ListTOString(',');
        }
        /// <summary>
        /// 获取角色列表用户
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETROLEUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new JH_Auth_RoleB().GetDTByCommand(" select RoleCode,RoleName,RoleDec from JH_Auth_Role where RoleCode=" + P1);
            dt.Columns.Add("UserRoleList", Type.GetType("System.Object"));
            foreach (DataRow row in dt.Rows)
            {
                row["UserRoleList"] = new JH_Auth_UserB().GetDTByCommand(@"select u.*,r.RoleName from JH_Auth_User u inner join dbo.JH_Auth_UserRole ur on   u.Username=ur.UserName
                                        inner join JH_Auth_Role r on ur.RoleCode=r.RoleCode where r.RoleCode=" + P1);
            }
            msg.Result = dt;
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">部门名称</param>
        /// <param name="P2">部门描述</param>
        /// <param name="strUserName"></param>
        public void ADDBRANCH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_Branch branch = new JH_Auth_Branch();
            branch = JsonConvert.DeserializeObject<JH_Auth_Branch>(P1);
            if (branch.DeptCode == 0)
            {
                branch.DeptRoot = 1;
                JH_Auth_Branch branch1 = new JH_Auth_BranchB().GetEntity(d => d.DeptName == branch.DeptName);
                if (branch1 != null)
                {
                    msg.ErrorMsg = "部门已存在";
                    return;
                }
                if (!new JH_Auth_BranchB().Insert(branch))
                {
                    msg.ErrorMsg = "添加部门失败";
                }
            }
            else
            {
                if (!new JH_Auth_BranchB().Update(branch))
                {
                    msg.ErrorMsg = "修改部门失败";
                }
            }
        }
        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETBRANCHBYCODE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int code = int.Parse(P1);
            msg.Result = new JH_Auth_BranchB().GetEntity(d => d.DeptCode == code);
        }
        /// <summary>
        /// 添加人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void ADDUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User user = new JH_Auth_User();
            user = JsonConvert.DeserializeObject<JH_Auth_User>(P1);
            if (user.ID != 0)
            {
                if (!new JH_Auth_UserB().Update(user))
                {
                    msg.ErrorMsg = "修改用户失败";
                }
            }
            else
            {
                JH_Auth_User user1 = new JH_Auth_UserB().GetEntity(d => d.UserName == user.UserName);
                if (user1 != null)
                {
                    msg.ErrorMsg = "用户已存在";
                    return;
                }
                if (!new JH_Auth_UserB().Insert(user))
                {
                    msg.ErrorMsg = "添加用户失败";
                }
            }

        }
        /// <summary>
        /// 更改用户是否禁用的状态
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">用户名</param>
        /// <param name="P2">状态</param>
        /// <param name="strUserName"></param>
        public void UPDATEUSERISUSE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User UPUser = new JH_Auth_UserB().GetEntities(d => d.UserName == P1).SingleOrDefault();
            UPUser.IsUse = P2;
            if (!new JH_Auth_UserB().Update(UPUser))
            {

                msg.ErrorMsg = "更新失败";
            }
        }
        /// <summary>
        /// 根据用户删除用户
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">用户名</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void DELUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (new JH_Auth_UserB().Delete(d => d.UserName == P1))
            {
                msg.ErrorMsg = "";
            }
            else
            {
                msg.ErrorMsg = P1 + "删除失败";
            }
        }
        public void GETUSERBYUSERNAME(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_User userModel = new JH_Auth_UserB().GetEntity(d => d.UserName == P1);
            msg.Result = userModel;
            msg.Result1 = new JH_Auth_BranchB().GetBranchNameByCode(userModel.BranchCode);
        }
        /// <summary>
        /// 根据用户名获取用户列表（多个用户以逗号隔开）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETUSERSBYUSERNAME(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            msg.Result = new JH_Auth_UserB().GetEntities(d => P1.Split(',').Contains(d.UserName));
        }
        /// <summary>
        /// 获取应用列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETAPPLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_FormBaseB().GetEntities();
        }
        /// <summary>
        /// 修改应用微信信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">修改的json</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void MODIFYAPPINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<JH_Auth_FormBase> formBaseList = JsonConvert.DeserializeObject<List<JH_Auth_FormBase>>(P1);
            foreach (JH_Auth_FormBase formBase in formBaseList)
            {
                new JH_Auth_FormBaseB().Update(formBase);
            }
        }
        /// <summary>
        /// 获取企业信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETCOMPANYINFO(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_QYB().GetEntities().FirstOrDefault();
        }
        /// <summary>
        /// 添加或编辑企业信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void EDITCOMPANY(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_QY company = new JH_Auth_QY();
            company = JsonConvert.DeserializeObject<JH_Auth_QY>(P1);
            if (company.ID != 0)
            {
                if (!new JH_Auth_QYB().Update(company))
                {
                    msg.ErrorMsg = "修改企业信息失败";
                }
            }
            else
            {
                JH_Auth_QY company1 = new JH_Auth_QYB().GetEntity(d => d.QYName == company.QYName);
                if (company1 != null)
                {
                    msg.ErrorMsg = "企业名称已存在";
                    return;
                }
                company.CRUser = "Admin";
                company.CRDate = DateTime.Now;
                if (!new JH_Auth_QYB().Insert(company))
                {
                    msg.ErrorMsg = "添加企业信息失败";
                }
            }
        }
        public void EDITCOMPANYQYH(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_QY company = JsonConvert.DeserializeObject<JH_Auth_QY>(P1);

            if (!new JH_Auth_QYB().Update(company))
            {
                msg.ErrorMsg = "修改企业号信息失败";
            }
        }


        /// <summary>
        /// 获取部门列表（选人页面使用）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETALLBMLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtBMS = new JH_Auth_BranchB().GetBranchListByCode(int.Parse(P1));
            dtBMS.Columns.Add("xsbm", Type.GetType("System.Object"));
            for (int i = 0; i < dtBMS.Rows.Count; i++)
            {
                dtBMS.Rows[i]["xsbm"] = new JH_Auth_BranchB().GetBranchListByCode(int.Parse(dtBMS.Rows[i]["DeptCode"].ToString()));
            }
            msg.Result = dtBMS;
        }

        /// <summary>
        /// 根据部门编号获取部门人员
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETUSERBYCODENEW(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int deptCode = 0;
            if (!int.TryParse(P1, out deptCode))
            {
                deptCode = 1;
            }
            DataTable dtBMUserS = new JH_Auth_UserB().GetUserListbyBranch(deptCode, P2);
            if (deptCode != 1)
            {
                DataTable dtBMS = new JH_Auth_BranchB().GetBranchListByCode(deptCode);
                for (int i = 0; i < dtBMS.Rows.Count; i++)
                {
                    DataTable dtTemp = new JH_Auth_UserB().GetUserListbyBranch(int.Parse(dtBMS.Rows[i]["DeptCode"].ToString()), P2);
                    if (dtTemp.Rows.Count != 0)
                    {
                        dtBMUserS.Merge(dtTemp);
                    }
                }
            }

            msg.Result = dtBMUserS;
        }

        public void GETWXUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            List<WXUserBR> list = new List<WXUserBR>();
            var listALL = new JH_Auth_BranchB().GetEntities().ToList();
            var list0 = listALL.Where(p => p.DeptRoot == 1).OrderBy(p => p.DeptShort).ToList();
            foreach (var v in list0)
            {
                WXUserBR wx = new WXUserBR();
                wx.DeptCode = v.DeptCode;
                wx.DeptName = v.DeptName;
                wx.DeptUser = new JH_Auth_UserB().GetEntities(d => d.BranchCode == v.DeptCode).ToList().Select(d => new { d.ID, d.UserName, d.UserRealName, d.telphone, d.zhiwu });

                GetNextWxUser(wx, listALL);
                list.Add(wx);
            }

            msg.Result = list;
        }

        public void GetNextWxUser(WXUserBR wx, List<JH_Auth_Branch> listALL)
        {
            var list = (from p in listALL
                        where p.DeptRoot == wx.DeptCode
                        orderby p.DeptShort
                        select new WXUserBR { DeptCode = p.DeptCode, DeptName = p.DeptName }).ToList();

            wx.SubDept = list;
            foreach (var v in list)
            {
                v.DeptUser = new JH_Auth_UserB().GetEntities(d => d.BranchCode == v.DeptCode).ToList().Select(d => new { d.ID, d.UserName, d.UserRealName, d.telphone, d.zhiwu });
                GetNextWxUser(v, listALL);
            }
        }

        /// <summary>
        /// P1:手机号，多个逗号(,)隔开
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg">手机号，多个逗号(,)隔开</param>
        /// <param name="P1"></param>
        /// <param name="P2">短信内容</param>
        /// <param name="UserInfo"></param>
        public void SENDSMS(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            CommonHelp.SendSMS(P1, P2);
        }

    }

    public class WXUserBR
    {
        public int DeptCode { get; set; }
        public string DeptName { get; set; }
        public dynamic DeptUser { get; set; }
        public List<WXUserBR> SubDept { get; set; }
    }

}